/*
 * Copyright 2002-2016 the atnoce.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.atnoce.onepass.view;

import com.atnoce.onepass.Start;
import com.atnoce.onepass.core.BackService;
import com.atnoce.onepass.core.SecurityController;
import com.atnoce.onepass.dao.OnepassConfigDao;
import com.atnoce.onepass.net.BasicNetService;
import com.atnoce.onepass.utils.Cache;
import com.atnoce.onepass.utils.CommonUtil;
import com.atnoce.onepass.utils.DbUtils;
import com.atnoce.onepass.utils.InitContext;
import com.jfoenix.controls.JFXTextField;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.util.Pair;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.Map;
import java.util.Optional;
import java.util.ResourceBundle;

/**
 * @author atnoce.com
 * @date 2016/11/6
 * @since 1.0.0
 */
public class BeforeLoginController implements Initializable{
    @FXML
    private Button createMainPassBtn;
    @FXML
    private Button loginColudServiceBtn;

    private Start start;
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        createMainPassBtn.setOnAction(e->createMainPass());
        loginColudServiceBtn.setOnAction(e->loginColudService());
    }
    public void setStart(Start start){
        this.start=start;
    }
    /**
     * 创建主密码
     */
    private void createMainPass(){
        Dialog<Pair<String,String>> dialog=new Dialog<>();
        dialog.setTitle("创建主密码");
        dialog.setHeaderText("正在创建主密码");
        dialog.setGraphic(new ImageView(this.getClass().getResource("image/createMainPass.png").toString()));

        ButtonType createBtnType=new ButtonType("创建", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(createBtnType,ButtonType.CANCEL);

        GridPane grid=new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20,150,10,10));

        JFXTextField oldPass=new JFXTextField();
        oldPass.setPromptText("输入主密码");
        oldPass.setPrefWidth(180.0);
        JFXTextField newPass=new JFXTextField();
        newPass.setPromptText("重复主密码");

        grid.add(new Label("输入主密码:"), 0, 0);
        grid.add(oldPass, 1, 0);
        grid.add(new Label("重复主密码:"), 0, 1);
        grid.add(newPass, 1, 1);

        Node lookupButton = dialog.getDialogPane().lookupButton(createBtnType);
        lookupButton.setDisable(true);

        newPass.textProperty().addListener((observable,oldValue,newValue)->{
            lookupButton.setDisable(!StringUtils.equals(oldPass.getText(), newValue));
        });

        dialog.getDialogPane().setContent(grid);

        Platform.runLater(()->oldPass.requestFocus());

        dialog.setResultConverter(dialogButton->{
            if(dialogButton==createBtnType){
                return new Pair<>(oldPass.getText(),newPass.getText());
            }
            return null;
        });

        Optional<Pair<String, String>> result = dialog.showAndWait();
        result.ifPresent(consumer->{
            String oldp=consumer.getKey();
            String newp=consumer.getValue();

            if(StringUtils.isEmpty(oldp)){
                CommonUtil.alert(Alert.AlertType.ERROR,"创建失败","密码不能为空","错误").showAndWait();
                return;
            }else if (oldp.length()>100){
                CommonUtil.alert(Alert.AlertType.ERROR,"创建失败","主密码长度不能超过100字符！","错误").showAndWait();
                return;
            }
            //openAll();
            //初始化数据库
            try{
                DbUtils.initTables(true);
            }catch(ClassNotFoundException e){
                CommonUtil.alert(Alert.AlertType.ERROR,"初始化数据库失败","找不到数据库驱动！"+e.getMessage(),"错误").showAndWait();
            }catch(SQLException e){
                CommonUtil.alert(Alert.AlertType.ERROR,"初始化数据库失败","发生内部错误！"+e.getMessage(),"错误").showAndWait();
            }
            //加密主密码
            String newMainPass= SecurityController.getSecurityInstence().encryptionMain(newp);
            //保存主密码
            OnepassConfigDao cd=new OnepassConfigDao();
            try {
                if(cd.updateMainPass(newMainPass)){
                    CommonUtil.alert(Alert.AlertType.INFORMATION,"主密码创建成功！","请务必牢记主密码，" +
                            "如果主密码忘记，您将无法打开onepass，并且我们也无法为您找回主密码！","成功").show();

                }else{

                }
                //显示登录界面
            } catch (SQLException ex) {
                CommonUtil.alert(Alert.AlertType.ERROR,"主密码设置失败","发生内部错误！"+ex.getMessage(),"错误").show();
                return;
            }catch(ClassNotFoundException e){
                CommonUtil.alert(Alert.AlertType.ERROR,"主密码设置失败","发生内部错误！"+e.getMessage(),"错误").show();
                return;
            }

            try {
                //更新配置文件
                InitContext.updateProperties("FIRSTSTART", "false");
                //只有成功更新配置文件后才可以进入主页面
                start.initLoginLayout(false);
            } catch (IOException ex) {
                CommonUtil.alert(Alert.AlertType.ERROR,"更新配置文件失败","更新系统配置文件发生异常!" +
                        "请重新设置主密码以尝试更新配置文件！错误信息："+ex.getMessage(),"错误").show();
            }
        });
    }
    /**
     * 登录云服务
     */
    private void loginColudService(){
        //服务端如果没有密码，那么应该如何绑定云账号？
        //不用管账号，错误的密码库无法打开
        Dialog<Pair<String,String>> dialog=new Dialog<>();
        dialog.setTitle("登录云账号");
        dialog.setHeaderText("请填写云账号信息");
        dialog.setGraphic(new ImageView(this.getClass().getResource("image/2_1.jpg").toString()));

        ButtonType createBtnType=new ButtonType("绑定",ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(createBtnType,ButtonType.CANCEL);

        GridPane grid=new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20,150,10,10));

        TextField coludAccount=new TextField();
        coludAccount.setPromptText("输入云账号");
        TextField bindCode=new TextField();
        bindCode.setPromptText("输入绑定号");

        grid.add(new Label("云账号:"), 0, 0);
        grid.add(coludAccount, 1, 0);
        grid.add(new Label("绑定号:"), 0, 1);
        grid.add(bindCode, 1, 1);
        dialog.getDialogPane().setContent(grid);

        Platform.runLater(()->coludAccount.requestFocus());

        dialog.setResultConverter(dialogButton->{
            if(dialogButton==createBtnType){
                return new Pair<>(coludAccount.getText(),bindCode.getText());
            }
            return null;
        });

        Optional<Pair<String, String>> result = dialog.showAndWait();
        result.ifPresent(consumer->{
            String account=consumer.getKey();
            String code=consumer.getValue();


            if(StringUtils.isBlank(account)){
                CommonUtil.alert(Alert.AlertType.ERROR,"绑定失败","云账号不能为空!","错误").showAndWait();
                return;
            }
            //校验云账号
            BasicNetService basicNetService=new BasicNetService();
            try {
                Map<String, Object> map = basicNetService.bindColudAccount(account);
                if((boolean)map.get("flag")){
                    //绑定成功
                    try{
                        DbUtils.initTables(false);
                        Cache.befortTempColudAccount=account;
                        //InitContext.updateProperties("COLUDACCOUNT", SecurityController.getSecurityInstence().encryptColudAccount(account, Cache.getKey()));
                        InitContext.updateProperties("FIRSTSTART","false");
                        InitContext.updateProperties("ACTIONCLOUD","true");

                        BackService.startSyncService(null,null,account);

                        start.initLoginLayout(true);

                    }catch(ClassNotFoundException e){
                        CommonUtil.alert(Alert.AlertType.ERROR,"初始化数据库失败","找不到数据库驱动！错误信息："+
                                e.getMessage(),"错误").showAndWait();
                    }catch(SQLException e){
                        CommonUtil.alert(Alert.AlertType.ERROR,"初始化数据库失败","发生内部错误！错误信息："+
                                e.getMessage(),"错误").showAndWait();
                    }

                }else{
                    //绑定失败
                    CommonUtil.alert(Alert.AlertType.ERROR,"绑定失败",(String)map.get("msg"),"错误").showAndWait();
                }
            } catch (Exception e) {
                CommonUtil.alert(Alert.AlertType.ERROR,"绑定失败","绑定出现问题!"+e.getMessage(),"错误").showAndWait();
                e.printStackTrace();
            }
        });
    }
}
